package com.atguigu.tingshu.album.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.mapper.*;
import com.atguigu.tingshu.album.service.BaseCategoryService;
import com.atguigu.tingshu.common.cache.TsCache;
import com.atguigu.tingshu.model.album.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@SuppressWarnings({"all"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;


    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private BaseAttributeMapper baseAttributeMapper;

    /**
     * 专辑三级分类查询
     *
     * @return
     */
    @Override
    public List<JSONObject> getBaseCategoryList() {

        // 初始化列表以存储最终的分层类别数据
        ArrayList<JSONObject> list = new ArrayList<>();

        // 从数据源检索所有基础类别列表
        List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);

        // 按Category1Id对类别进行分组
        Map<Long, List<BaseCategoryView>> baseCategoryViewListMap = baseCategoryViewList.stream()
                .collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));

        // 遍历每个顶级类别（Category1）
        for (Map.Entry<Long, List<BaseCategoryView>> listEntry1 : baseCategoryViewListMap.entrySet()) {
            Long category1Id = listEntry1.getKey();
            List<BaseCategoryView> categoryViewList1 = listEntry1.getValue();

            // 为Category1创建一个JSON对象
            JSONObject category1 = new JSONObject();
            category1.put("categoryId", category1Id);
            category1.put("categoryName", categoryViewList1.get(0).getCategory1Name());

            // 在Category1内按Category2Id对类别进行分组
            Map<Long, List<BaseCategoryView>> categoryViewListMap = categoryViewList1.stream()
                    .collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            ArrayList<JSONObject> category2Child = new ArrayList<>();

            // 遍历每个二级类别（Category2）
            for (Map.Entry<Long, List<BaseCategoryView>> listEntry2 : categoryViewListMap.entrySet()) {
                Long category2Id = listEntry2.getKey();
                List<BaseCategoryView> categoryViewList2 = listEntry2.getValue();

                // 为Category2创建一个JSON对象
                JSONObject category2 = new JSONObject();
                category2.put("categoryId", category2Id);
                category2.put("categoryName", categoryViewList2.get(0).getCategory2Name());
                ArrayList<JSONObject> category3Child = new ArrayList<>();

                // 遍历每个三级类别（Category3）在Category2内
                for (BaseCategoryView categoryView3 : categoryViewList2) {
                    Long category3Id = categoryView3.getCategory3Id();
                    String category3Name = categoryView3.getCategory3Name();

                    // 为Category3创建一个JSON对象
                    JSONObject category3 = new JSONObject();
                    category3.put("categoryId", category3Id);
                    category3.put("categoryName", category3Name);
                    category3Child.add(category3);
                }

                // 将Category3的JSON对象列表添加到Category2
                category2.put("categoryChild", category3Child);
                category2Child.add(category2);
            }

            // 将Category2的JSON对象列表添加到Category1
            category1.put("categoryChild", category2Child);
            list.add(category1);
        }

        // 返回分层类别数据的JSON对象列表
        return list;
    }

    /**
     * 根据一级分类id获取属性数据
     *
     * @param category1Id
     * @return
     */
    @Override
    public List<BaseAttribute> findAttribute(Long category1Id) {
        return baseAttributeMapper.selectAttributeList(category1Id);
    }

    /**
     * 根据三级分类id查询分类信息
     *
     * @param category3Id
     * @return
     */
    @TsCache(prefix = "category:info:")
    @Override
    public BaseCategoryView getCategoryView(Long category3Id) {
        BaseCategoryView baseCategoryView = baseCategoryViewMapper.selectById(category3Id);
        return baseCategoryView;
    }

    /**
     * 根据id获取全部数据
     *
     * @param category1Id
     * @return
     */
    @Override
    public JSONObject getBaseCategoryListById(Long category1Id) {
        //  根据一级分类id获取一级分类信息
        BaseCategory1 baseCategory1 = baseCategory1Mapper.selectById(category1Id);
        JSONObject category1 = new JSONObject();
        category1.put("categoryId", baseCategory1.getId());
        category1.put("categoryName", baseCategory1.getName());
        LambdaQueryWrapper<BaseCategory2> baseCategory2LambdaQueryWrapper = new LambdaQueryWrapper<>();
        baseCategory2LambdaQueryWrapper.eq(BaseCategory2::getCategory1Id, category1Id);
        //  根据一级分类id获取二级分类信息
        List<BaseCategory2> baseCategory2List = baseCategory2Mapper.selectList(baseCategory2LambdaQueryWrapper);
        List<JSONObject> categoryChild2List = baseCategory2List.stream().map(baseCategory2 -> {
            JSONObject category2 = new JSONObject();
            category2.put("categoryId", baseCategory2.getId());
            category2.put("categoryName", baseCategory2.getName());
            LambdaQueryWrapper<BaseCategory3> baseCategory3LambdaQueryWrapper = new LambdaQueryWrapper<>();
            baseCategory3LambdaQueryWrapper.eq(BaseCategory3::getCategory2Id, baseCategory2.getId());
            //  根据二级分类id获取三级分类信息
            List<BaseCategory3> baseCategory3List = baseCategory3Mapper.selectList(baseCategory3LambdaQueryWrapper);
            List<JSONObject> categoryChild3List = baseCategory3List.stream().map(baseCategory3 -> {
                JSONObject category3 = new JSONObject();
                category3.put("categoryId", baseCategory3.getId());
                category3.put("categoryName", baseCategory3.getName());
                return category3;
            }).collect(Collectors.toList());
            category2.put("categoryChild", categoryChild3List);
            return category2;
        }).collect(Collectors.toList());
        category1.put("categoryChild", categoryChild2List);
        return category1;
    }

    /**
     * 获取一级分类下置顶到频道页的三级分类列表
     *
     * @param category1Id
     * @return
     */
    @Override
    public List<BaseCategory3> findTopBaseCategory3ByCategory1Id(Long category1Id) {
        //先根据一级分类id查询二级分类的集合
        //创建LambdaQueryWrapper对象
        LambdaQueryWrapper<BaseCategory2> baseCategory2LambdaQueryWrapper = new LambdaQueryWrapper<>();
        //设置查询条件，一级分类id等于category1Id
        baseCategory2LambdaQueryWrapper.eq(BaseCategory2::getCategory1Id, category1Id);
        //根据查询条件查询二级分类的集合
        List<BaseCategory2> baseCategory2List = baseCategory2Mapper.selectList(baseCategory2LambdaQueryWrapper);
        //将二级分类的id集合提取出来
        List<Long> category2IdList = baseCategory2List.stream().map(BaseCategory2::getId).collect(Collectors.toList());
        //根据二级分类id查询三级分类的集合
        LambdaQueryWrapper<BaseCategory3> baseCategory3LambdaQueryWrapper = new LambdaQueryWrapper<>();
        //设置查询条件，二级分类id在category2IdList中
        baseCategory3LambdaQueryWrapper.in(BaseCategory3::getCategory2Id, category2IdList);
        //设置查询条件，是否置顶为1
        baseCategory3LambdaQueryWrapper.eq(BaseCategory3::getIsTop, 1);
        //设置查询条件，限制查询结果为7条
        baseCategory3LambdaQueryWrapper.last(" limit 7 ");
        //执行查询操作，返回查询结果
        return baseCategory3Mapper.selectList(baseCategory3LambdaQueryWrapper);
    }
}
